package com.zllkj.mm.module.moment

import android.content.Intent
import android.text.TextUtils
import android.util.Log
import android.view.MenuItem
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.kennyc.bottomsheet.BottomSheetListener
import com.kennyc.bottomsheet.BottomSheetMenuDialogFragment
import com.kennyc.bottomsheet.menu.BottomSheetMenu
import com.zllkj.mm.R
import com.zllkj.mm.adapter.NearByFriendListAdapter
import com.zllkj.mm.api.network.RetrofitHelper
import com.zllkj.mm.api.network.RxHelper
import com.zllkj.mm.api.network.subscriber.ProgressSubscriber
import com.zllkj.mm.base.BaseAppFragment
import com.zllkj.mm.common.ClientConfig
import com.zllkj.mm.common.L
import com.zllkj.mm.model.entity.CollectionsListBean
import com.zllkj.mm.model.entity.DynamicSubscriptionVo
import com.zllkj.mm.model.entity.GridImageViewBean
import com.zllkj.mm.module.goods.vm.ItemCollectionsVM
import com.zllkj.mm.module.shopping.fragment.OrderListItemFragment
import com.zllkj.mm.module.shopping.vm.ItemFriendListVM
import com.zllkj.mm.util.common.AppUtils
import com.zllkj.mm.util.common.FormatUtil
import kotlinx.android.synthetic.main.fragment_mycollection.view.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlin.collections.ArrayList

class FriendListFragment(val loadingType: Int,val dataType:Int) : BaseAppFragment() {

    lateinit var dataAdapter: NearByFriendListAdapter
    var datas = ArrayList<ItemFriendListVM>()
    var currentPage = 1

    override fun getLayoutId(): Int {
        return R.layout.fragment_mycollection
    }

    override fun loadData() {
        super.loadData()

        dataAdapter = NearByFriendListAdapter(R.layout.item_friend_list_data, datas, this)
        mRootView?.smartRefreshlayout_mycollection?.setOnRefreshListener {
            datas.clear()
            currentPage = 1
            loadNetWorkData(OrderListItemFragment.PULL_DOWN)
        }

        mRootView?.smartRefreshlayout_mycollection?.setOnLoadMoreListener {
            currentPage += 1
            loadNetWorkData(OrderListItemFragment.LOAD_MORE)
        }

        dataAdapter.setOnItemClickListener { baseQuickAdapter, view, i ->
            Log.d("acthome","on click1")
            addFragment(FriendDetailFragment(datas[i]))
        }
        dataAdapter.setOnItemChildClickListener { baseQuickAdapter, view, i ->
            if (view.id == R.id.moreIv){
                Log.d("acthome","on click2")
                showBlockOptionDialog(i)
            } else if (view.id == R.id.ll_like_area) {
                likeOrUnlike(i)
            } else {
                addFragment(FriendDetailFragment(datas[i]))
            }
        }

        mRootView?.rv_mycollection?.apply {
            layoutManager = LinearLayoutManager(requireContext())
            adapter = dataAdapter
        }

        loadNetWorkData(OrderListItemFragment.PULL_DOWN)
    }

    fun likeOrUnlike(position: Int){
        if (datas[position].userDyBean?.liked == 0) { //未点赞
            addSubscribe(RetrofitHelper.getInstance().dynamicApi.likeDynamic((java.util.HashMap<String, Any>().apply {
                this["dynamicId"] = datas[position].userDyBean?.dynamicId.toString()
            })).compose<String>(RxHelper.defaultHandleResult<String>()).subscribe(object : ProgressSubscriber<String>(requireContext()){
                override fun onSucc(t: String?) {
                    datas[position].userDyBean?.liked = 1
                    datas[position].userDyBean?.likeNum = datas[position].userDyBean?.likeNum!! +1
                    dataAdapter.notifyItemChanged(position)


                }

                override fun onError(e: Throwable?) {
                    super.onError(e)
                }

            }))
        } else {
            addSubscribe(RetrofitHelper.getInstance().dynamicApi.cancelLikeDynamic((java.util.HashMap<String, Any>().apply {
                this["dynamicId"] = datas[position].userDyBean?.dynamicId.toString()
            })).compose<String>(RxHelper.defaultHandleResult<String>()).subscribe(object : ProgressSubscriber<String>(requireContext()){
                override fun onSucc(t: String?) {
                    datas[position].userDyBean?.liked = 0
                    datas[position].userDyBean?.likeNum = datas[position].userDyBean?.likeNum!! - 1
                    dataAdapter.notifyItemChanged(position)


                }

                override fun onError(e: Throwable?) {
                    super.onError(e)
                }

            }))
        }

    }

    override fun notifyDataUpdate(intent: Intent?) {
        super.notifyDataUpdate(intent)
        if (intent?.action == BaseAppFragment.ACTION_FRAGMENT_UPDATE){
            if (intent?.getBooleanExtra(AppUtils.KEY_OF_REFRESH_MOMENT_LIST,false) == true){
                datas.clear()
                currentPage = 1
                loadNetWorkData(OrderListItemFragment.PULL_DOWN)
            }

        }
    }

    fun followOrUnFollow(type:Int,position: Int){
        if(type == 1) {
            addSubscribe(RetrofitHelper.getInstance().dynamicApi.followUserFollow((java.util.HashMap<String, Any>().apply {
                this["fansId"] = datas[position].userDyBean?.userId.toString()
            })).compose<String>(RxHelper.defaultHandleResult<String>()).subscribe(object : ProgressSubscriber<String>(requireContext()){
                override fun onSucc(t: String?) {
                    datas[position].userDyBean?.fanType = 1


                }

                override fun onError(e: Throwable?) {
                    super.onError(e)
                }

            }))
        } else {
            addSubscribe(RetrofitHelper.getInstance().dynamicApi.cancelUserFollow((java.util.HashMap<String, Any>().apply {
                this["fansId"] = datas[position].userDyBean?.userId.toString()
            })).compose<String>(RxHelper.defaultHandleResult<String>()).subscribe(object : ProgressSubscriber<String>(requireContext()){
                override fun onSucc(t: String?) {

                    datas[position].userDyBean?.fanType = 0
                }

                override fun onError(e: Throwable?) {
                    super.onError(e)
                }

            }))
        }
    }

    fun blockUser(isOnlyOne:Int,position: Int) {
        addSubscribe(RetrofitHelper.getInstance().dynamicApi.addBlockUserOrDynamic((java.util.HashMap<String, Any>().apply {
            this["dynamicId"] = datas[position].userDyBean?.dynamicId.toString()
            this["onlyOne"] = isOnlyOne
        })).compose<String>(RxHelper.defaultHandleResult<String>()).subscribe(object : ProgressSubscriber<String>(requireContext()){
            override fun onSucc(t: String?) {
                datas.clear()
                loadNetWorkData(PULL_DOWN)

            }

            override fun onError(e: Throwable?) {
                super.onError(e)
            }

        }))

    }

    fun badMomentReport(position: Int){
        addSubscribe(RetrofitHelper.getInstance().dynamicApi.reportErrorDynamic((java.util.HashMap<String, Any>().apply {
            this["dynamicId"] = datas[position].userDyBean?.dynamicId.toString()
        })).compose<String>(RxHelper.defaultHandleResult<String>()).subscribe(object : ProgressSubscriber<String>(requireContext()){
            override fun onSucc(t: String?) {
                    L.showToast("举报成功")
            }

            override fun onError(e: Throwable?) {
                super.onError(e)
            }

        }))
    }

    fun showBlockOptionDialog(position:Int){
        var listener = object : BottomSheetListener {
            override fun onSheetDismissed(bottomSheet: BottomSheetMenuDialogFragment, `object`: Any?, dismissEvent: Int) {

            }

            override fun onSheetItemSelected(bottomSheet: BottomSheetMenuDialogFragment, item: MenuItem, `object`: Any?) {
                if(item.itemId == R.id.menu_block_follow) {
                    followOrUnFollow(1,position)
                } else if (item.itemId == R.id.menu_block_jubao) {
                    badMomentReport(position)
                } else if (item.itemId == R.id.menu_block_moment) {
                    blockUser(1,position)
                } else if (item.itemId == R.id.menu_block_user) {
                    blockUser(0,position)
                } else if (item.itemId == R.id.menu_block_un_follow) {
                    followOrUnFollow(0,position)
                }

            }

            override fun onSheetShown(bottomSheet: BottomSheetMenuDialogFragment, `object`: Any?) {

            }

        }

       if (datas[position].userDyBean?.fanType == 0){
           BottomSheetMenuDialogFragment.Builder(context = requireContext(),
                   sheet = R.menu.menu_block_dialog,
                   listener = listener,
                   title = "请选择",
                   `object` = "")
                   .show(childFragmentManager)
       } else {
           BottomSheetMenuDialogFragment.Builder(context = requireContext(),
                   sheet = R.menu.menu_block_dialog_follow,
                   listener = listener,
                   title = "请选择",
                   `object` = "")
                   .show(childFragmentManager)
       }


    }

    fun loadNetWorkData(loadType: Int) {
        if (loadingType == 0) {
            addSubscribe(RetrofitHelper.getInstance().api.dynamicNearbyList((HashMap<String, Any>().apply {
                this["currentPage"] = currentPage
                this["pageSize"] = 10
                this["sex"] = ""
                this["dynamicType"] = ""
                this["latitude"] = AppUtils.lat
                this["longitude"] = AppUtils.lat
                this["content"] = ""
            })).compose<DynamicSubscriptionVo>(RxHelper.defaultHandleResult<DynamicSubscriptionVo>()).subscribe(object : ProgressSubscriber<DynamicSubscriptionVo>(context) {
                override fun onSucc(t: DynamicSubscriptionVo?) {
                    t?.records?.let {
                         GlobalScope.launch(Dispatchers.IO) {
                            t?.records?.let {
                                it.filter { it.dynamicType == dataType || it.dynamicType != 0 }.mapIndexed { index, dynamicSubscriptionRecordVo ->
                                    var vm = ItemFriendListVM()
                                    vm.userDyBean = dynamicSubscriptionRecordVo

                                    if (!TextUtils.isEmpty(dynamicSubscriptionRecordVo.videoUrl)) {
                                        var array = dynamicSubscriptionRecordVo?.pic.split(",")
                                        var gb = GridImageViewBean().apply {
                                            videoUrl = ClientConfig.IMG_URL + dynamicSubscriptionRecordVo.videoUrl
                                            
                                            array.map { if (!TextUtils.isEmpty(it)) url = it }
                                        }
                                        vm.imageList.add(gb)
                                    } else {
                                        var array = dynamicSubscriptionRecordVo?.pic.split(",")
                                        array.mapIndexed { index, it ->
                                            if (!TextUtils.isEmpty(it)) {
                                                var gb = GridImageViewBean().apply {
                                                    url = it
                                                }
                                                vm.imageList.add(gb)
                                            }
                                        }
                                    }
                                    datas.add(vm)
                                }
                            }

                            GlobalScope.launch(Dispatchers.Main) {
                                dataAdapter.notifyDataSetChanged()
                                if (loadType == OrderListItemFragment.PULL_DOWN) {
                                    mRootView?.smartRefreshlayout_mycollection?.finishRefresh()
                                    mRootView?.findViewById<RecyclerView>(R.id.rv_orderlist_recycleview)?.adapter = dataAdapter
                                } else if (loadType == OrderListItemFragment.LOAD_MORE) {
                                    dataAdapter.notifyDataSetChanged()
                                    mRootView?.smartRefreshlayout_mycollection?.finishLoadMore()
                                } else {
                                    dataAdapter.notifyDataSetChanged()
                                }

                            }
                        }

                    }

                }

                override fun onError(e: Throwable?) {
                    super.onError(e)

                }
            }))

        } else {
            addSubscribe(RetrofitHelper.getInstance().api.dynamicSubscriptionList((HashMap<String, Any>().apply {
                this["currentPage"] = currentPage
                this["pageSize"] = 5
                this["sex"] = ""
                this["dynamicType"] = ""
                this["latitude"] = AppUtils.lat
                this["longitude"] = AppUtils.lat
                this["content"] = ""
            })).compose<DynamicSubscriptionVo>(RxHelper.defaultHandleResult<DynamicSubscriptionVo>()).subscribe(object : ProgressSubscriber<DynamicSubscriptionVo>(context) {
                override fun onSucc(t: DynamicSubscriptionVo?) {
                    t?.records?.let {
                        it.filter { it.dynamicType == dataType || it.dynamicType != 0 }.mapIndexed { index, dynamicSubscriptionRecordVo ->
                            var vm = ItemFriendListVM()
                            vm.userDyBean = dynamicSubscriptionRecordVo
                            if (!TextUtils.isEmpty(dynamicSubscriptionRecordVo.videoUrl)) {
                                var array = dynamicSubscriptionRecordVo?.pic.split(",")
                                var gb = GridImageViewBean().apply {
                                    videoUrl = ClientConfig.IMG_URL + dynamicSubscriptionRecordVo.videoUrl

                                    array.map { if (!TextUtils.isEmpty(it)) url = it }
                                }
                                vm.imageList.add(gb)
                            } else {
                                var array = dynamicSubscriptionRecordVo?.pic.split(",")
                                array.mapIndexed { index, it ->
                                    if (!TextUtils.isEmpty(it)) {
                                        var gb = GridImageViewBean().apply {
                                            url = it
                                        }
                                        vm.imageList.add(gb)
                                    }
                                }
                            }
                            datas.add(vm)
                        }
                    }
                    dataAdapter.notifyDataSetChanged()
                    if (loadType == OrderListItemFragment.PULL_DOWN) {
                        mRootView?.smartRefreshlayout_mycollection?.finishRefresh()
                        mRootView?.findViewById<RecyclerView>(R.id.rv_orderlist_recycleview)?.adapter = dataAdapter
                    } else if (loadType == OrderListItemFragment.LOAD_MORE) {
                        mRootView?.smartRefreshlayout_mycollection?.finishLoadMore()
                        dataAdapter.notifyDataSetChanged()
                    } else {
                        dataAdapter.notifyDataSetChanged()
                    }

                }

                override fun onError(e: Throwable?) {
                    super.onError(e)

                }
            }))
        }
    }
}